<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :permission="permissionList"
        v-bind="bindVal"
        v-on="onEvent"
        :data="tableData"
        :page.sync="page"
        :search.sync="searchForm"
        @search-change="searchChange"
        @selection-change="selectionChange"
      >
        <template slot="search" slot-scope="{row,size}">
          <el-form-item label="提交状态">
          <el-select v-model="searchForm.confirmStatus" clearable :size="size" placeholder="请选择">
            <el-option
              type="select"
              placeholder="提交状态">
              <el-option value="0" label="未提交"></el-option>
              <el-option value="1" label="已提交"></el-option>
            </el-option>
          </el-select>
          </el-form-item>
          <el-form-item label="日期">
            <el-date-picker
              clearable
              v-model="searchForm.statisticsDate"
              value-format='yyyy-MM-dd'
              type="date"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </template>
        <template slot="menuLeft">
          <el-button type="primary" size="small" @click="myAdd">添加</el-button>
          <el-upload
            class="upload-inline"
            action=""
            :show-file-list="false"
            accept="xsl,xsls"
            :http-request="handleImport">
            <el-button type="primary" size="small">导 入</el-button>
          </el-upload>
          <el-button type="primary" size="small" @click="downTemplate">模板下载</el-button>
          <el-button type="primary" size="small" :loading="ishandleLoading" @click="handleExcelWrite">导 出</el-button>
          <el-button type="primary" size="small" @click="submitBefore">提 交</el-button>
          <el-button type="primary" size="small" @click="generateReport">生成日报表</el-button>
          <el-button type="primary" size="small" @click="delBatch">删 除</el-button>
          <el-button type="primary" size="small" :hidden="true" v-if="false" @click="handlePrint">打 印</el-button>
          <el-button type="primary" size="mini" @click="submitData">加入报表差错</el-button>
        </template>
        <template slot="menu" slot-scope="{row, index}">
          <el-button type="text" size="small"
            icon="el-icon-edit"
            v-if="row.confirmStatus!='1'"
            @click="rowEdit(row, index)">编 辑</el-button>
          <!-- <el-button type="text" size="small"
            icon="el-icon-edit"
            v-if="row.reportModifyStatus=='1' && row.confirmStatus=='0'"
            @click="reportEdit(row, index)">编 辑</el-button> -->
          <el-button type="text" size="small"
            icon="el-icon-delete"
            v-if="row.confirmStatus!='1'"
            @click="handleDel(row, index)">删 除</el-button>
          <el-button
            icon="el-icon-check"
            type="text"
            size="small"
            @click="openPastRecords(row)"
            >查看历史记录</el-button
          >
        </template>
      </avue-crud>
    </basic-container>
    <el-dialog
      :visible.sync="dialogFormVisible"
      title="选择生成日期"
      width="30%"
      @close="dialogFormVisible=false">
      <el-form>
        <el-form-item label="日期" v-loading="isShowLoading" element-loading-text = "正在生成日报表，请稍后..." element-loading-spinner = "el-icon-loading" >
          <el-date-picker
            :size="size"
            v-model="generateStatisticsDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="日期">
          </el-date-picker>
        </el-form-item>
        <el-button type="primary" :disabled="btn" @click="generateReportSubmit">确定</el-button>
      </el-form>
    </el-dialog>
    <open-dialog
      :DialogVisible.sync="visableDialogRecords"
      title="查看历史记录"
      width="60%"
    >
      <avue-crud
        :data="recordsData"
        :option="tableOptionRecords">
      </avue-crud>
      <div class="bottom-menu-close">
        <el-button type="primary" @click="visableDialogRecords=false"
          >取消</el-button
        >
      </div>
    </open-dialog>
    <add-edit ref="addEdit" v-if="addVisableDialog"></add-edit>
    <addReportEditor ref="addReportEditor" @addReportSuccess="getList"></addReportEditor>
  </div>
</template>

<script>
  import { importBatch, updateSwStStock, generateReport, downTemplate, fetchList,getTypeValue,delBatch,queryRecords } from '@/api/subwaystm/swststock';
  import { tableOptionRecords } from '@/const/crud/subwaystm/swststock';
  import {getTicketCheckOfSubmit} from "@/api/subwaystm/swstticketcheck";
  import baseCrud from '@/mixins/base-crud';
  import {updateSwStTicketInformationCheck} from "../../../api/clarifyManagement/HKCZTJPKXX";
  import fileDownload from 'js-file-download';
  import { handleExcelResponse } from "@/util/util";
  import AddEdit from "./addEdit";
  import { dateFormat } from "@/util/date";
  import transitUtil from "@/api/subwayRat/transitUtil";
  import request from "@/router/axios";
  import addReportEditor from '@/views/stationTiecketManager/xianWngCJXXQR/BBCCGG/BBCCGGSQ/Editor';
  export default {
    name: 'swststock',
    components: {AddEdit,addReportEditor},
    mixins: [baseCrud('subwaystm/swststock')],
    data() {       
      return {
        formData: {},
	showType:1,
        ids:[],
        addVisableDialog:false,
        tableData: [],
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 50, // 每页显示多少条
        },
        tableDataCash: [],
        tableDataEle: [],
        dialogFormVisible:false,
        statisticsDate:'',
	generateStatisticsDate:'',
        searchForm: {
          statisticsDate : '',
	  ticketTypeEn : '',
	  ticketTypeParamEn : ''
        },
        checkDay:25,
        checkDate:'',
        btn: false,
        isShowLoading: false,
        checkData: {},
        ishandleLoading: false,
        visableDialogRecords: false,
        recordsData: [],
        tableOptionRecords: tableOptionRecords,
        selectKeys:[]
      }
    },
    created() {
      let now = new Date();
      getTypeValue('check_day').then(response => {
        this.checkDay = parseInt(response.data.data[0].value);
        this.checkDate = dateFormat(now).substr(0, 8) + this.checkDay;
      });
      now.setDate(now.getDate() - 1);
      this.searchForm.statisticsDate = dateFormat(now).substr(0, 10);
      this.otherVueAction();
    },
    computed: {
      permissionList() {
        return {
          addBtn: this.vaildData(this.permissions.swststock_add, false),
          delBtn: this.vaildData(this.permissions.swststock_del, true),
          editBtn: this.vaildData(this.permissions.swststock_edit, false)
        };
      }
    },
    methods: {       
      async submitData() {
        if (this.$refs.crud.tableSelect.length < 1) {
          this.$message.error("请选择数据");
          return false;
        }
        if (this.$refs.crud.tableSelect.length != 1) {
          this.$message.error("只能选择一条数据");
          return false;
        }
        let res = false;
        let ress = false;
        for (const table of this.$refs.crud.tableSelect) {
          if (table.confirmStatus != "1") {
            this.$message.error("请选择已提交的数据");
            return false;
          }else{
            if (table.isAddReprotError == "1") {
              res = await this.$confirm('该数据已加入报表差错，是否重新加入？', '提示', {
                confirmButtonText: '是',
                cancelButtonText: '否',
                type: 'warning'
              });
              if (!res) {
                return;
              }else{
                ress = true;
              }
            }
          }
        }
        if(res==false){
          ress = await this.$confirm("是否加入报表差错", "提示", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning"
          });
        }
        if (!ress) {
          return;
        }
        this.selectKeys = this.$refs.crud.tableSelect;
        let param={
          dialogTitle: "加入报表差错",
          diffAmountId:this.selectKeys[0].id,
          dataSourceTable:"sw_st_stock",
          lineCode:this.selectKeys[0].lineCode,
          stationCode:this.selectKeys[0].stationCode,
          reprotTime:this.selectKeys[0].statisticsDate,
          reportNameId:12,
          settleBeginTime:this.selectKeys[0].statisticsDate,
          settleEndTime:this.selectKeys[0].statisticsDate,
          showType:3,
          dataSource:1
        };
        this.$refs.addReportEditor.others_report_add_call(param);
      },
      async queryPastRecords(row){
        let param={};
        param.id=row.id;
        var that = this
        await queryRecords(param)
          .then(res => {
            this.recordsData = res.data.data;
          })
      },
      openPastRecords(row){
        this.queryPastRecords(row);
        this.visableDialogRecords=true;
      },
      // getList(page, params) {
      //   return fetchList(
      //     Object.assign(
      //       {
      //         current: page.currentPage,
      //         size: page.pageSize,
      //       },
      //       params,
      //       this.searchForm
      //     )
      //   ).then((response) => {
      //     this.tableData = response.data.data.records;
      //     this.page.total = response.data.data.total;
      //   });
      // },
      searchChange(form, done) {
       	if(form!=null && form.ticketTypeEn!=''){
	   this.searchForm.ticketTypeEn = form.ticketTypeEn;
	}
	if(form!=null && form.ticketTypeParamEn!=''){
	   this.searchForm.ticketTypeParamEn = form.ticketTypeParamEn;
	}

        this.getList(this.page, this.searchForm).then(() => {
          done();
        });
      },
      handleDel(row, index) {
        this.$refs.crud.rowDel(row, index)
      },
      rowEdit: function(row) {
        this.showType = 1;
        this.addVisableDialog = true;
        this.$nextTick(() => {
          this.$refs.addEdit.recallShow(row);
        });
      },
      // reportEdit: function(row) {
      //   this.showType = 3;
      //   this.addVisableDialog = true;
      //   this.$nextTick(() => {
      //     this.$refs.addEdit.recallShow(row);
      //   });
      // },
      myAdd: function() {
        this.showType = 0;
        this.addVisableDialog = true;
        this.$nextTick(() => {
          this.$refs.addEdit.recallShow(null);
        });
      },
      addchangeDialog: function() {
        if (this.addchangeDialogFlag) {
          this.addchangeDialogFlag = false;
        } else {
          this.addchangeDialogFlag = true;
        }
      },
      downTemplate(){
        downTemplate().then((response)=>{
          // fileDownload(response.data,"车站车票库存日报表模板.xlsx");
          handleExcelResponse(response,"车站车票库存日报表模板.xls");
        });
      },
      generateReport(){
        let now = new Date();
        now.setDate(now.getDate() - 1);
        this.generateStatisticsDate = dateFormat(now).substr(0, 10);
        //this.generateStatisticsDate = new Date(new Date().getTime() - (1000 * 60 * 60 * 24));
        this.dialogFormVisible = true;
      },
      async getTicketChecks(){
        let now = new Date();
        let date = dateFormat(now).substr(0, 8)+ this.checkDay;
        await getTicketCheckOfSubmit(date)
          .then(response => {
            this.checkData = response.data.data;
          })
      },
      async generateReportSubmit(){
        this.btn = true;
        this.isShowLoading = true;
        await generateReport({lineCode:this.$store.getters.userInfo.lineCode,stationCode:this.$store.getters.userInfo.stationCode,statisticsDate:this.generateStatisticsDate}).then((response)=>{
          let code = response.data.code;
          if(0 == code){
            this.$message.success('生成成功');
            this.btn = false;
            this.isShowLoading = false;
          }else{
            this.$message.error(response.data.msg);
            this.btn = false;
            this.isShowLoading = false;
          }
        }).catch(() => {
            this.btn = false;
            this.isShowLoading = false;
        });
        this.getList(this.page);
        this.dialogFormVisible = false;
      },
      submitBefore(){
        this.checkData = {};
        if(this.ids.length<=0){
          this.$message.warning("请选择要提交的数据！");
          return;
        }
        for (const table of this.$refs.crud.tableSelect) {
          if (table.confirmStatus == "1") {
            this.$message.error("选择数据已经提交，请勿重复提交！");
            return false;
          }
        }
        let generateDate = null;
        for (let i = 0; i < this.$refs.crud.tableSelect.length; i++) {
          generateDate = this.$refs.crud.tableSelect[0].statisticsDate;
        }
        let now = new Date();
        let date = dateFormat(now).substr(0, 8)+ this.checkDay;
        if(generateDate == date){
          this.getTicketChecks().then(response =>{
            if(this.validatenull(this.checkData)){
              this.$confirm("本月车票盘点数据未录入或已录入但未提交，需先提交车票盘点数据，请确认是否继续提交库存日报表?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }).then(() => {
                this.submit();
              });
            }else{
              this.$confirm("是否确认提交库存日报表?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }).then(() => {
                this.submit();
              });
            }
          });
        }else{
          this.$confirm("是否确认提交库存日报表?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            this.submit();
          });
        }
      },
      async submit(){
        await updateSwStStock(this.ids,this.checkDate).then((response)=>{
        });
        this.$message.success("提交成功");
        this.getList(this.page);
      },
      // handleImport(item){
      //   let file = item.file
      //   let param = new FormData()
      //   param.append('file',file)
      //   importBatch(param).then(() => {
      //     this.$message.success('导入成功')
      //     this.getList(this.page)
      //   })
      // },
      handleImport(item) {//
        this.$message.warning("正在导入，请耐心等待！");
        let file = item.file;
        let param = new FormData();
        param.append("file", file);
        importBatch(param).then(() => {
          this.$notify({
            title: "成功",
            message: "导入成功",
            type: "success",
            duration: 2000
          });
          this.getList(this.page);
        });
      },
      // 导出车站车票库存日报表
      async handleExcelWrite() {
        this.ishandleLoading = true;
        this.$message.warning("正在导出，请稍后！");
        //let res = 
        await request({
          url:
            "/stm/swststock/export/" +
            this.searchForm.statisticsDate,
          method: "get",
          responseType: "blob",
          headers: {
            "Content-Type": "application/json;charset=UTF-8"
          }
        }).then((res)=>{
          handleExcelResponse(res, "车站车票库存日报表.xlsx");
          this.ishandleLoading = false;
          this.$message.success("导出成功！");
        }).catch(() => {
          this.ishandleLoading = false;
          this.$message.success("导出失败！");
        })
      },
      selectionChange(list){
        this.ids = list.map(function(value,index,array){
          return value.id
        })
      },
      delBatch: function () {
        if (this.$refs.crud.tableSelect.length < 1) {
          this.$message.error("请选择数据！");
          return false;
        }
        let ids = [];
        for (const table of this.$refs.crud.tableSelect) {
          if (table.confirmStatus != "0") {
            this.$message.error("请选择未提交的数据");
            return false;
          }
          ids.push(table.id);
        }
        this.$confirm("确认删除?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          delBatch(ids)
            .then((data) => {
              this.$message.success("删除成功");
              this.getList(this.page);
              done();
            })
            .catch(() => {
              loading();
            });
        });
      },
      otherVueAction(){
        transitUtil.$on('updateReport_call_12',(param)=>{
	  //alert("获取查询条件333-otherVueAction---"+JSON.stringify(param))
          let p=param;

	  if(param!=null && param.ticketTypeEn!=''){
	     this.searchForm.ticketTypeEn = param.ticketTypeEn;
	  }
	  if(param!=null && param.ticketTypeParamEn!=''){
	     this.searchForm.ticketTypeParamEn = param.ticketTypeParamEn;
	  }
          this.searchForm.statisticsDate = param.statisticsDate;
          fetchList(Object.assign({
            current: this.page.currentPage,
            size: this.page.pageSize
          }, p)).then(response => {
            this.tableData = response.data.data.records
            this.page.total = response.data.data.total
            this.tableLoading = false
          })
        });
      }
    }
  }
</script>

<style scoped>
/* 旋转效果 */
.demo-spin-icon-load{
    animation: ani-demo-spin 1s linear infinite;
}
@keyframes ani-demo-spin {
   from { transform: rotate(0deg);}
   50% { transform: rotate(180deg);}
   to { transform: rotate(360deg);}
}
/* 假如内容过长，一屏放不下，滚动条下拉覆盖不全 */
.ivu-spin-fix {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 8;
    width: 100%;
    height: 100%;
    background-color: hsla(0,0%,100%,.9);
}
.bottom-menu-close {
  margin-top: 18px;
  text-align: center;
}
</style>
